#include "plane.hpp"

Plane::Plane() : _n( 0.f, 0.f, 1.f ), _o(), color( 1 ) {}

Plane::Plane( vec3f n, vec3f o ) : _n( n ), _o( o ), color( 1 ) {
  _n.normalized();
}

Plane::Plane( vec3f v1, vec3f v2, vec3f v3, vec3f o ) : _o( o ), color( 1 ) {
  _n = cross( v2 - v1, v3 - v1 );
  _n.normalized();
}

bool Plane::parallel( const Ray &r ) const {
  if ( dot( r.direction(), _n ) != 0 ) {
    return false;
  }
  return true;
}

bool Plane::hit( const Ray &r, f32 tmin, f32 tmax, f32 time,
                 HitRecord &record ) {
  bool hitted = false;
  float t1 = dot( r( tmin ) - _o, _n );
  float t2 = dot( r( tmax ) - _o, _n );
  hitted = ( !parallel( r ) ) && ( t1 * t2 <= 0 );
  if ( hitted ) {
    record.color = color;
    record.normal = _n;
    // FIXME: precsion error
    if ( t1 == 0.f )
      record.t = tmin;
    else if ( t2 == 0.f )
      record.t = tmax;
    else {
      vec3f ro = r.origin() - _o;
      float ndotOminusA = -dot( _n, ro );
      float ndotd = dot( _n, r.direction() );
      record.t = ndotOminusA / ndotd;
    }
  }
  return hitted;
}

bool Plane::shadowHit( const Ray &r, f32 tmin, f32 tmax, f32 time ) {
  bool hitted = false;

  return false;
}